<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" :inline="true" >
      <el-form-item label="流程名称" prop="flowName">
        <el-input
          v-model="queryParams.flowName"
          placeholder="请输入流程名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
         <el-button type="primary" size="small" icon="el-icon-plus"
         v-hasPermi="['labbase:project_creation:edit']" @click="handleAdd">发起流程</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="project_creationList" @selection-change="handleSelectionChange">
      <el-table-column label="编号" prop="instanceId" width="60"/>
      <el-table-column label="流程名称"  prop="flowName" :show-overflow-tooltip="true" />
      <el-table-column label="项目类型"  prop="labProjectOpt" :formatter="labProjectOptFormat" :show-overflow-tooltip="true" />
      <el-table-column label="项目名称"  prop="projectName" :show-overflow-tooltip="true" />
      <el-table-column label="开始日期"  prop="projectStart" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.projectStart, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期"  prop="projectEnd" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.projectEnd, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
       <el-table-column label="提交时间" prop="startTime" width="160px">
      </el-table-column>
      <el-table-column label="执行步骤" prop="nodeName" align="center" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.flowStatusOpt=='uncommitted'"
            v-hasPermi="['labbase:project_creation:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.flowStatusOpt=='uncommitted'"
            v-hasPermi="['labbase:project_creation:edit']"
          >删除</el-button>
              <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"

          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目创建申请对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-tabs v-model="activeName">
        <el-tab-pane label="项目创建流程表单" name="first"></el-tab-pane>
        <el-tab-pane label="流程导入" name="second" v-if="form.instanceId">
          <FlowChoose ref="workFlow" @workflow="setWorkflow" :id="form.workflowId" :businessType="form.businessTypeOpt"></FlowChoose>
        </el-tab-pane>
      </el-tabs>
     <el-form ref="form" :model="form" :rules="rules" label-width="100px" v-if="activeName=='first'">
      <el-row>
         <el-col :span="12" style="margin-left: 20px">
         <el-form-item label="流程创建" prop="flowCreation">
          <span class="flowStyle">{{form.flowCreation}}</span>
        </el-form-item>
        </el-col>
        <el-col :span="10">
            <div style="float:right">
              <el-button :class="showCopy?'active dis_active':'active'"  @click="showCopy=showCopy?false:true" type="text">任务抄送
              </el-button>
            </div>
          </el-col>
      </el-row>
       <el-form-item label="任务抄送" prop="copyToUsers" v-show="showCopy">
          <div class="purchase_s_view">
            <el-input v-model="choosedUserName" placeholder="抄送人员" style="width: 430px;" />
			<el-button type="primary" @click="selectUser" plain>选择用户</el-button>
          </div>
        </el-form-item>
      <el-row>
        <el-col :span="22">
        <el-form-item label="流程名称" prop="flowName">
          <el-input v-model="form.flowName" placeholder="请输入流程名称" class="form_long"/>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
        <el-form-item label="项目类型" prop="labProjectOpt" >
         <div v-if="form.instanceId > 0">
          <el-select v-model="form.labProjectOpt" placeholder="请选择项目类型" class="form_long" disabled >
            <el-option
              v-for="dict in labProjectOptOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
         </div>
         <div v-else>
          <el-select v-model="form.labProjectOpt" placeholder="请选择项目类型" class="form_long" >
            <el-option
              v-for="dict in labProjectOptOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
         </div>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" placeholder="请输入项目名称" class="form_long"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
        <el-form-item label="开始日期" prop="projectStart">
          <el-date-picker clearable size="small"
            v-model="form.projectStart" style="width:200px ;"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择项目开始日期">
          </el-date-picker>
        </el-form-item>
        </el-col>
         <el-col :span="11">
        <el-form-item label="结束日期" prop="projectEnd">
          <el-date-picker clearable size="small" style="width:200px ;"
            v-model="form.projectEnd"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择项目结束日期">
          </el-date-picker>
        </el-form-item>
        </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
          <el-form-item label="填报人工号" prop="createBy">
           <el-input v-model="form.createBy" disabled class="form_short"/>
          </el-form-item>
          </el-col>
           <el-col :span="11">
          <el-form-item label="填报人姓名" prop="createNickName">
            <el-input v-model="form.createNickName" disabled class="form_short"/>
          </el-form-item>
          </el-col>
          </el-row>
         <div v-if="form.labProjectOpt==1">
         <ProjectInstrument ref="instrument" :instrument="form.labProjectInstrument"></ProjectInstrument>
        </div>
         <div v-if="form.labProjectOpt==2">
         <ProjectWorkResearch ref="workResearch" :workResearch="form.labProjectWorkResearch"></ProjectWorkResearch>
        </div>
         <div v-if="form.labProjectOpt==3">
         <ProjectConstruction ref="construction" :construction="form.labProjectConstruction"></ProjectConstruction>
        </div>
         <div v-if="form.labProjectOpt==4">
         <ProjectTeachingCultivation ref="teachingCultivation" :teachingCultivation="form.labProjectTeachingCultivation"></ProjectTeachingCultivation>
        </div>
         <div v-if="form.labProjectOpt==5">
         <ProjectDevelopmentProject ref="developmentProject" :developmentProject="form.labProjectDevelopmentProject"></ProjectDevelopmentProject>
        </div>
        <el-row>
            <el-col :span="22">
              <el-form-item label="附件" >
                <UploadCom ref="upload" @submitData="submitData"  description="" :userFileList="fileList" class="form_long"/>
              </el-form-item>
              </el-col>
              <el-col :span="22">
              <el-form-item label="备注说明" prop="comments" >
                <el-input v-model="form.comments" type="textarea" rows="4"   placeholder="请输入内容" class="form_long"/>
              </el-form-item>
              </el-col>
         </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
         <el-button type="primary" @click="submitForm" v-if="activeName=='first'"
         v-hasPermi="['labbase:project_creation:edit']">保存</el-button>
        <el-button type="primary" @click="submitWorkflow" v-if="activeName=='second'">提交</el-button>
        <el-button @click="cancel">关闭</el-button>
      </div>
    </el-dialog>
	<ChooseUser @chooseUsers="getUser" ref="checkedUserCom"></ChooseUser>
    <ProjectDetails  ref="previewCom" />
  </div>
</template>

<script>
import { commitProject_creation,listProject_creation, getProject_creation, delProject_creation, addProject_creation, updateProject_creation, exportProject_creation } from "@/api/labbase/project_creation";
import {searchEmployee,getCheckedList} from "@/api/labdata/employee";
import { formatCurrentDate } from "@/utils/index";
import { getUserProfile } from "@/api/system/user";
import {treeselect } from "@/api/labdata/orgnization";
import ProjectDetails from "@/views/labbase/project_creation/projectDetail.vue";
import UploadCom from "@/views/labdata/commons/upload.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import FlowChoose from '@/views/labdata/flowDefination/flow_choose.vue'
import ChooseUser from "@/views/labdata/employee/user_choose_com.vue";
import ProjectWorkResearch from "@/views/labbase/project_creation/projectWorkSearch.vue";
import ProjectInstrument from "@/views/labbase/project_creation/projectInstrument.vue";
import ProjectConstruction from "@/views/labbase/project_creation/projectConstruction.vue";
import ProjectTeachingCultivation from "@/views/labbase/project_creation/projectTeachingCultivation.vue";
import ProjectDevelopmentProject from "@/views/labbase/project_creation/projectDevelopmentProject.vue";

export default {
  name: "Project_creation",
  components:{UploadCom,ProjectDetails,Treeselect,FlowChoose,ChooseUser,
    ProjectWorkResearch,ProjectInstrument,ProjectConstruction,ProjectTeachingCultivation,ProjectDevelopmentProject},
  data() {
    return {
      checkedUserList: [],
      choosedUserName: '',
      // 流程状态字典
      flowStatusOptOptions: [],
      showCopy: false,
      activeName: "first",
      //用户对象
      user:{},
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 项目创建申请表格数据
      project_creationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 项目类型字典
      labProjectOptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createUserId: null,
        flowName: null,
        labProjectOpt: null,
        projectName: null,
        departmentOrgId: null,
        budgetFunds: null,
        projectOwnerId: null,
        contactPhone: null,
        comments: null,
        projectStart: null,
        projectEnd: null,
        ownerTitle: null,
        ownerEmail: null
      },
      //附件集合
      fileList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        createUserId: [
          { required: true, message: "创建人员不能为空", trigger: "blur" }
        ],
        flowName: [
          { required: true, message: "流程名称不能为空", trigger: "blur" }
        ],
        labProjectOpt: [
          { required: true, message: "项目类型不能为空", trigger: "change" }
        ],
        projectStart: [
          { required: true, message: "项目开始日期不能为空", trigger: "blur" }
        ],
        projectEnd: [
          { required: true, message: "项目结束日期不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
      checkedUserList: function(val) {
        this.choosedUserName = '';
        this.form.copyToUsers = '';
        val.forEach((item, index) => {
          if (index > 0) {
            this.choosedUserName += ",";
            this.form.copyToUsers += ",";
          }
          this.choosedUserName += item.nickName;
          this.form.copyToUsers += item.userId;
        })
      },
    },
  created() {
    this.getList();
    //this.getDeptList();
    this.getUserInfo();
    this.getTreeselect();
    this.getDicts("labProjectOpt").then(response => {
      this.labProjectOptOptions = response.data;
    });
    this.getDicts("flowStatusOpt ").then(response => {
        this.flowStatusOptOptions = response.data;
      });

  },

  methods: {
	  selectUser(){
		if(this.checkedUserList && this.checkedUserList.length>0){
			this.$refs["checkedUserCom"].handleAdd(this.checkedUserList);
		}else{
			this.$refs["checkedUserCom"].handleAdd();
		}
	  },
	  getUser(e) {
        //console.log(JSON.stringify(e));
        this.checkedUserList = e;
      },
      setWorkflow(workflowId) {
        this.form.workflowId = workflowId;
        //console.log('workflow='+workflowId);
      },
      submitWorkflow() {
		if(!this.form.workflowId){
			this.form.workflowId = this.$refs["workFlow"].getWorkflowId();
		}
        this.form.createBy = this.$store.state.user.name;
        commitProject_creation(this.form).then((response) => {
          this.msgSuccess("提交成功");
          this.open = false;
          this.getList();
        });
      },


     /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
    //查询当前用户信息
    getUserInfo() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    /** 查询部门列表 */
    getDeptList() {
      this.loading = true;
      this.queryParams={}
      listOrgnization(this.queryParams).then(response => {
        this.deptList =response.rows;
      });
    },
    searchUser(){
        // console.log(this.form.projectOwnerId);
        if(!this.form.projectOwnerId){
          this.form.projectLeader = null;
          this.form.ownerTitle = null;
          return;
        }
         searchEmployee(this.form.projectOwnerId).then(response=>{
           let searchResult = response.data;
           if(searchResult){
             this.form.projectLeader = searchResult.nickName;
             this.form.ownerTitle =searchResult.title
           }else{
             this.form.projectLeader = null;
             this.form.ownerTitle = null;
           }
           //强制刷新
           this.$forceUpdate();
          });
      },

    /** 查询项目创建申请列表 */
    getList() {
      this.loading = true;
      listProject_creation(this.queryParams).then(response => {
        this.project_creationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 项目类型字典翻译
    labProjectOptFormat(row, column) {
      return this.selectDictLabel(this.labProjectOptOptions, row.labProjectOpt);
    },
    // 取消按钮
    cancel() {
      this.showCopy = false;
      this.open = false;
      this.reset();
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        flowCreation: formatCurrentDate()+this.user.nickName+"创建",
        instanceId: null,
        createTime: null,
        createUserId: null,
        flowName: null,
        labProjectOpt: null,
        projectName: null,
        departmentOrgId: null,
        budgetFunds: null,
        projectOwnerId: null,
        contactPhone: null,
        comments: null,
        projectStart: null,
        projectEnd: null,
        title: null,
        ownerEmail: null,
        imageFileId: null
      };
      this.activeName='first';
      this.checkedUserList = [];
      this.showCopy = false;
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.instanceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.createBy = this.$store.state.user.name;
      this.form.createNickName = this.$store.state.user.nickName;
      this.open = true;
      this.title = "添加项目创建";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const instanceId = row.instanceId || this.ids
      getProject_creation(instanceId).then(response => {
        this.form = response.data;
        this.fileList = this.form.images;
        if(this.form.copyToUsers!=null){
          getCheckedList({checkedUserIds:this.form.copyToUsers}).then(res=>{
            this.checkedUserList = res.data;
            this.showCopy = true;
          });
        }
        this.open = true;
        this.searchUser();
        this.title = "修改项目创建";
      });
    },
    /**查看 */
    handleDetail(row){
        this.$refs['previewCom'].handleUpdate(row);
    },

 /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$refs["upload"].doSubmit();
        }
      });
    },

    /** 提交按钮 */
    submitData(fileList) {
      this.form.images = fileList;
      // 实验仪器
      if(this.form.labProjectOpt==1){
          this.form.labProjectInstrument = this.$refs["instrument"].getInstrument();
        }
      // 工作研究
      if(this.form.labProjectOpt==2){
          this.form.labProjectWorkResearch = this.$refs["workResearch"].getWorkResearch();
        }
      // 建设项目
      if(this.form.labProjectOpt==3){
          this.form.labProjectConstruction = this.$refs["construction"].getConstruction();
        }
      // 教学培育
      if(this.form.labProjectOpt==4){
          this.form.labProjectTeachingCultivation = this.$refs["teachingCultivation"].getTeachingCultivation();
        }
      // 开发项目
      if(this.form.labProjectOpt==5){
          this.form.labProjectDevelopmentProject = this.$refs["developmentProject"].getDevelopmentProject();
        }

      if (this.form.instanceId != null) {
         this.form.createBy = this.$store.state.user.name;
        updateProject_creation(this.form).then(response => {
          this.msgSuccess("修改成功");
          this.form = response.data;
          this.fileList = this.form.images;
          this.$forceUpdate();
          // this.open = false;
          this.getList();
          this.activeName = "second";
        });
      } else {
        addProject_creation(this.form).then(response => {
          this.msgSuccess("新增成功");
          this.form = response.data;
          this.fileList = this.form.images;
          // this.open = false;
          this.getList();
           this.activeName = "second";
        });
      }

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const instanceIds = row.instanceId || this.ids;
      this.$confirm('是否确认删除项目创建申请编号为"' + instanceIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delProject_creation(instanceIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
     // 流程状态字典翻译
      flowStatusOptFormat(row, column) {
        return this.selectDictLabel(this.flowStatusOptOptions, row.flowStatusOpt);
      },
    /** 导出按钮操作 */
    // handleExport() {
    //   const queryParams = this.queryParams;
    //   this.$confirm('是否确认导出所有项目创建申请数据项?', "警告", {
    //       confirmButtonText: "确定",
    //       cancelButtonText: "取消",
    //       type: "warning"
    //     }).then(function() {
    //       return exportProject_creation(queryParams);
    //     }).then(response => {
    //       this.download(response.msg);
    //     })
    // },
  }
};
</script>
<style type="text/css" scoped>
  .form_long{
    width:502px;
  }
  .form_short{
    width:200px;
  }
  .el-button.active{
    text-decoration: underline;
    color: #0000ee;
  }
  .el-button.dis_active {
    color: #999999
  }
  .select_view {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
   .purchase_s_view {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
</style>
